package com.adtech.adms.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.adtech.adms.commons.ErrorCode;
import com.adtech.adms.commons.tree.TreeNode;
import com.adtech.adms.commons.tree.TreeNodeImpl;
import com.adtech.adms.system.LogConstants;
import com.adtech.adms.system.SystemConstants;
import com.adtech.adms.system.dao.FeatureDAO;
import com.adtech.adms.system.pojo.Feature;
import com.adtech.adms.system.pojo.Role;
import com.adtech.adms.system.pojo.User;
import com.adtech.adms.system.service.RoleService;
import com.adtech.core.cache.Cache;
import com.adtech.core.dao.HibernateDAO;
import com.adtech.core.dao.exp.Condition;
import com.adtech.core.dao.exp.Expression;
import com.adtech.core.dao.query.Pager;
import com.adtech.core.dao.query.QueryConstants;
import com.adtech.core.dao.query.QueryCriterions;
import com.adtech.core.dao.query.Sort;
import com.adtech.core.exception.ServiceException;

/**
 * 角色service实现类
 * 实现角色模块业务操作
 * @author Dormin 
 * @since 2011-8-11 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class RoleServiceImpl implements RoleService {

	private HibernateDAO dao;
	private FeatureDAO featureDAO;
	private Cache templateCache;
	private Cache userFeatureTreeCache;

	public void setFeatureDAO(FeatureDAO featureDAO) {
		this.featureDAO = featureDAO;
	}

	public Logger logger = null;

	public RoleServiceImpl() {
		logger = Logger.getLogger(this.getClass());
	}

	/**
	 * 获取所有的Role对象
	 */
	public List<Role> getRoleList(Pager pager) {
		return (List<Role>) dao.getByQuery(Role.class, pager, null, null);
	}

	public Cache getTemplateCache() {
		return templateCache;
	}

	public void setTemplateCache(Cache templateCache) {
		this.templateCache = templateCache;
	}

	public Cache getUserFeatureTreeCache() {
		return userFeatureTreeCache;
	}

	public void setUserFeatureTreeCache(Cache userFeatureTreeCache) {
		this.userFeatureTreeCache = userFeatureTreeCache;
	}




    /**
	 * 删除一个角色
	 * 
	 * @param t
	 * @return
	 * @throws ServiceException
	 */
	public void delete(String id,User user) throws ServiceException {
		if (logger.isDebugEnabled()) {
			logger.debug("RoleManager的delete方法删除角色");
		}
		try {
            if(id==null || id.length()==0) {
                return;
            }
            String[] ids = id.split(",");
            for(String roleId : ids) {
                if(roleId!=null && roleId.length()>0) {
                    Role role = dao.getById(Role.class, Long.parseLong(roleId));
                    if(role.getUsers()!=null && role.getUsers().size()>0) {
                    	throw new ServiceException(ErrorCode.ROLE_HAS_USER);
                    }
                    dao.delete(role);
                    
                }
            }
			//dao.deletes(Role.class, id);
		} catch (ServiceException e) {
			logger.error(e.getMessage());
			throw e;
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServiceException(0);
		}
	}

	/**
	 * 保存一个角色
	 * 
	 * @param t
	 * @return
	 * @throws ServiceException
	 */
	public void save(Role role,User user) throws ServiceException {
		if (logger.isDebugEnabled()) {
			logger.debug("RoleManager的save方法添加角色");
		}
		List<Feature> features=new ArrayList<Feature>();
		try {
			if (role.getRoleId() == null) {

				for (Feature feature : role.getFeatures()) {
					if(feature.isChecked()) {
						features.add((Feature)featureDAO.loadById(Feature.class, feature.getId()));
					}
				}
				role.setFeatures(features);
				dao.add(role);
			} else {
				Role newRole=(Role)dao.loadById(Role.class, role.getRoleId());
				List<Feature> fs=newRole.getFeatures();
				for (Feature feature : role.getFeatures()) {
					Feature oldFeature = (Feature)featureDAO.loadById(Feature.class, feature.getId());
					if(feature.isChecked()) {
						if(feature.isAllCheck()) {
							List<Feature> allFeatureList = featureDAO.getSubFeatureList(feature.getId());
							for(Feature f : allFeatureList) {
								fs.remove(f);
								fs.add(f);
							}
						}
						else {
							fs.remove(oldFeature);
							fs.add(oldFeature);
						}
					}
					else {
						if(feature.isAllCheck()) {
							List<Feature> allFeatureList = featureDAO.getSubFeatureList(feature.getId());
							for(Feature f : allFeatureList) {
								fs.remove(f);
							}
						}
						fs.remove(oldFeature);
					}
				}
				newRole.setFeatures(fs);
				newRole.setDesc(role.getDesc());
				newRole.setRoleName(role.getRoleName());
				dao.saveOrUpdate(newRole);
				List<User> userList = featureDAO.getByQuery(User.class, Condition.eq(SystemConstants.User.ROLES_ID, newRole.getRoleId()));
				for(User u : userList) {
					templateCache.remove(u.getUserId());
					userFeatureTreeCache.remove(u.getUserId());
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServiceException(0);
		}
	}

	/**
	 * 更新角色
	 * 
	 * @param t
	 * @return
	 */
	public boolean saveorUpdate(Role role) {
		if (logger.isDebugEnabled()) {
			logger.debug("RoleManager的saveorUpdate方法更新角色");
		}
		try {

			dao.saveOrUpdate(role);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage());
			return false;
		}
	}

	/**
	 * 得到列表的模型数据
	 * 
	 * @param pager
	 * @param sHql
	 * @param hqlSort
	 * @return
	 */
	public List<Role> getRoleList(Pager pager, Expression expression, Sort sort) {
		return (List<Role>)dao.getByQuery(Role.class, pager, expression, sort);
	}

	/**
	 * 根据主键获取角色
	 */
	public Role getRoleById(Long roleId) {
		Role role=dao.getById(Role.class, roleId);
		for (Feature feature :role.getFeatures()) {
			dao.initialize(feature);
		}
		return role;
	}

	public boolean check(Role role) {
		QueryCriterions qc = new QueryCriterions();
		qc.and(SystemConstants.Role.ROLE_NAME, role.getRoleName(), QueryConstants.EQ);
		qc.and(SystemConstants.Role.ROLE_ID, role.getRoleId(), QueryConstants.NE);

		return dao.getByQuery(Role.class, qc.toExpression()).size() == 0;
	}

	public List<Feature> getFeaturesNotRole(Role role) {
		List<Feature> features= (List<Feature>) featureDAO.getByQuery(Feature.class, null);
		List<Role> roles=new ArrayList<Role>();
		roles.add(role);
		List<Feature> roleFeatures=featureDAO.getFeaturesByRoles(roles);

		for (Iterator<Feature> iterator = features.iterator(); iterator.hasNext();) {
			Feature feature =  iterator.next();
			for (Feature roleReature : roleFeatures) {
				if(feature.getId().equals(roleReature.getId())){
					iterator.remove();
				}
			}
		}

		return features;
	}

	public List<TreeNode<Object>> getRoleTree() {
		List<Role> roles=(List<Role>)dao.getByQuery(Role.class, null);

		List<TreeNode<Object>> nodes=new ArrayList<TreeNode<Object>>();
		for (Role role : roles) {
			TreeNodeImpl	node=new TreeNodeImpl();
			node.setName(role.getRoleName());
			node.setId(role.getRoleId());
			nodes.add(node);
		}
		return nodes;
	}

	public void setDao(HibernateDAO dao) {
		this.dao = dao;
	}

}
